package cn.com.cifi.mars.web.action.sync;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import cn.com.cifi.mars.bean.bo.PriceCoreValueBO;
import cn.com.cifi.mars.bean.bo.SysLogBO;
import cn.com.cifi.mars.bean.param.esb.EsbCoreValueVO;
import cn.com.cifi.mars.bean.param.esb.EsbInfo;
import cn.com.cifi.mars.bean.param.esb.EsbInfoReq;
import cn.com.cifi.mars.bean.param.esb.EsbReturnVo;
import cn.com.cifi.mars.bean.param.esb.EsbXgReqParam;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.constants.VersionConstant;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.constant.Constants;
import cn.com.cifi.mars.constant.IsDeleteEnum;
import cn.com.cifi.mars.constant.IsSuccessEnum;
import cn.com.cifi.mars.constant.LogEventEnum;
import cn.com.cifi.mars.constant.LogSrcEnum;
import cn.com.cifi.mars.constant.LogTypeEnum;
import cn.com.cifi.mars.constant.MarketingEunm;
import cn.com.cifi.mars.constant.VersionStatusEnum;
import cn.com.cifi.mars.constant.VersionTypeEunm;
import cn.com.cifi.mars.constant.WhetherEnum;
import cn.com.cifi.mars.entity.BudgetLockRecord;
import cn.com.cifi.mars.entity.DmOdsMyVsMarsSContract;
import cn.com.cifi.mars.entity.MdmGroupBld;
import cn.com.cifi.mars.entity.MdmProject;
import cn.com.cifi.mars.entity.MdmProjectPatner;
import cn.com.cifi.mars.entity.MdmStage;
import cn.com.cifi.mars.entity.PriceVersion;
import cn.com.cifi.mars.entity.ProjectLockRecord;
import cn.com.cifi.mars.entity.common.ProjectByStages;
import cn.com.cifi.mars.mapper.mars.PriceVersionMapper;
import cn.com.cifi.mars.mapper.mars.ProjectByStagesMapper;
import cn.com.cifi.mars.mapper.mars.ProjectLockRecordMapper;
import cn.com.cifi.mars.service.BudgetLockRecordService;
import cn.com.cifi.mars.service.BudgetVersionIdentifyService;
import cn.com.cifi.mars.service.BuildAreaService;
import cn.com.cifi.mars.service.DmOdsMyVsMarsSContractService;
import cn.com.cifi.mars.service.GroupBldService;
import cn.com.cifi.mars.service.MonthTradePlanService;
import cn.com.cifi.mars.service.MymRoomInfoService;
import cn.com.cifi.mars.service.OrgService;
import cn.com.cifi.mars.service.PanoplanBuildPlanItemDetailService;
import cn.com.cifi.mars.service.PanoplanBuildPlanItemService;
import cn.com.cifi.mars.service.PanoplanBuildPlanService;
import cn.com.cifi.mars.service.PanoramaService;
import cn.com.cifi.mars.service.PriceVersionGroupService;
import cn.com.cifi.mars.service.PriceVersionService;
import cn.com.cifi.mars.service.PriceVersionValueOrgService;
import cn.com.cifi.mars.service.ProjectLockRecordDetailService;
import cn.com.cifi.mars.service.ProjectLockRecordService;
import cn.com.cifi.mars.service.ProjectPatnerService;
import cn.com.cifi.mars.service.ProjectService;
import cn.com.cifi.mars.service.SignPlanVersionDetailService;
import cn.com.cifi.mars.service.SignPlanVersionService;
import cn.com.cifi.mars.service.StagePartNersService;
import cn.com.cifi.mars.service.StageService;
import cn.com.cifi.mars.service.SysLogService;
import cn.com.cifi.mars.service.SysProjectFetchNumberService;
import cn.com.cifi.mars.util.BasicAuthClient;
import cn.com.cifi.mars.util.DateUtils;
import cn.com.cifi.mars.util.ExceptionUtils;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import cn.com.cifi.mars.util.StrUtils;
import cn.com.cifi.mars.util.SynchrolockUtil;
import cn.com.cifi.mars.util.WebUtils;
import cn.com.cifi.mars.util.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
public class EsbController extends BaseAction implements  IEsbController{
	
    private static final Logger logger = LoggerFactory.getLogger(EsbController.class);

    @Autowired
    PanoplanBuildPlanService panoplanBuildPlanService;
    @Autowired
    PanoplanBuildPlanItemService panoplanBuildPlanItemService;
    @Autowired
    PanoplanBuildPlanItemDetailService panoplanBuildPlanItemDetailService;
    @Autowired
    private GroupBldService groupBldService;
    @Autowired
	private StageService stageService;
    @Autowired
    private BuildAreaService buildAreaService;
    @Autowired
    private ProjectPatnerService projectPatnerService;
    @Autowired
    private ProjectService projectService;
    @Autowired
	private SysLogService sysLogService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private PriceVersionValueOrgService priceVersionValueOrgService;
    @Autowired
    private MonthTradePlanService monthTradePlanService;
    @Autowired
    private SignPlanVersionService signPlanVersionService;
	@Autowired
	private MymRoomInfoService mymRoomInfoService;
	@Autowired
	private StagePartNersService stagePartNersService;
	@Autowired
	private PanoramaService panoramaService;
	@Autowired
	private SynchrolockUtil synchrolockUtil;
	@Autowired
	private PriceVersionService priceVersionService;
	@Autowired
	private ProjectLockRecordService projectLockRecordService;
	@Autowired
	private ProjectLockRecordDetailService projectLockRecordDetailService;
	@Autowired
	private ProjectLockRecordMapper projectLockRecordMapper;
	@Autowired
	private PriceVersionMapper priceVersionMapper;
	@Autowired
	private ProjectByStagesMapper projectByStagesMapper;
	@Autowired
	private SysProjectFetchNumberService sysProjectFetchNumberService;
	@Autowired
	private SignPlanVersionDetailService signPlanVersionDetailService;
	@Autowired
	private DmOdsMyVsMarsSContractService dmOdsMyVsMarsSContractService;
	@Autowired
	private BudgetVersionIdentifyService budgetVersionIdentifyService;
	@Autowired
	private BudgetLockRecordService budgetLockRecordService;
	@Autowired
	private PriceVersionGroupService priceVersionGroupService;
    
	@Value("${buildPlan_url}")
	private String buildPlan_url;
	
	@Value("${buildPlan_file_path}")
	private String buildPlan_file_path;
	
	@Value("${xg_query_url}")
    private String xgQueryUrl;
    
    @Value("${api_name}")
	private String apiName;
	
	@Value("${api_key}")
	private String apiKey;
	
    @Override
    public String project(String apiVersion, String projectInfo) {
    	log.info("######ESB主数据项目 start##################："+ LocalDateTime.now());
		JSONObject object = (JSONObject) JSONObject.parse(projectInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		List<String> projectIds = new ArrayList<>();
    	String returnStatus = "S";
        String returnMsg = "调用成功";
        String ex ="成功";
        String isSuccess = IsSuccessEnum.SUCCESS.getKey();
    	String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		try {
			JSONObject projectInfoObj =  JSON.parseObject(projectInfo);
			JSONArray projects = projectInfoObj.getJSONObject("requestInfo").getJSONObject("project").getJSONArray("projectInfoLine");
			if(projects != null && !projects.isEmpty()) {
				for(int i =0; i < projects.size(); i ++ ) {
					JSONObject  projectObj = projects.getJSONObject(i);
					String projectId = projectObj.getString("projectId");
					projectIds.add(projectId);
					MdmProject mdmProject = projectService.selectByProjectId(projectId,IsDeleteEnum.NO.getKey());
					if(mdmProject == null) {
						mdmProject = new MdmProject();
						mdmProject.setProjectId(projectObj.getString("projectId"));
						if(StringUtils.isNotEmpty(projectObj.getString("isDelete"))){
							mdmProject.setIsDelete(projectObj.getString("isDelete"));
		                }else{
		                	mdmProject.setIsDelete(IsDeleteEnum.NO.getKey()+"");
		                }
						mdmProject.setCreatedTime(LocalDateTime.now());
						setProjectValue(projectObj, mdmProject);
						projectService.save(mdmProject);
					}else {
						setProjectValue(projectObj, mdmProject);
						mdmProject.setUpdatedTime(LocalDateTime.now());
						projectService.updateByProjectId(mdmProject);
					}
				}
			}
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "N";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//调用组织机构同步
		Thread  syncOrgFromIdm = new SyncOrgFromIdm(projectIds);
		syncOrgFromIdm.start();
		
		//记录日志
		Thread  saveLog = new SaveLog("项目数据","接收参数："+projectInfo+";处理结果："+ex,isSuccess);
		saveLog.start();
		
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		String returnCode = "SMS-006";
		
		log.info("######ESB主数据项目 end##################:"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,returnCode);
    }

	private void setProjectValue(JSONObject projectObj, MdmProject Project) {
		Project.setProjectCode(projectObj.getString("projectCode"));
		Project.setProjectName(projectObj.getString("projectName"));
		Project.setProjectOldName(projectObj.getString("projectOldName"));
		Project.setKingdeeProjectId(projectObj.getString("kingdeeProjectID"));
		Project.setLegalCompD(projectObj.getString("legalCompID"));
		Project.setLegalCompName(projectObj.getString("legalCompName"));
		Project.setCompanyId(projectObj.getString("companyID"));
		Project.setCompanyName(projectObj.getString("companyName"));
		Project.setDomeOver(projectObj.getString("domeOver"));
		Project.setOrgId(projectObj.getString("orgID"));
		Project.setOrgName(projectObj.getString("orgName"));
		Project.setProjectType(projectObj.getString("projectType"));
		Project.setIsAndTable(projectObj.getString("isAndTable"));
		Project.setTradeMode(projectObj.getString("tradeMode"));
		Project.setIsCoopProject(projectObj.getString("isCoopProject"));
		Project.setStagesNum(projectObj.getString("stagesNum"));
		Project.setProjectStatusCode(projectObj.getString("projectStatusCode"));
		Project.setProjectStatus(projectObj.getString("projectStatus"));
		Project.setProductLine(projectObj.getString("productLine"));
		Project.setCaseName(projectObj.getString("caseName"));
		Project.setProjectClassify(projectObj.getString("projectClassify"));
		Project.setCityType(projectObj.getString("cityType"));
		Project.setProjectStage(projectObj.getString("projectStage"));
		Project.setDevelopmeType(projectObj.getString("developmeType"));
		Project.setLinkProjectId(projectObj.getString("linkProjectID"));
		Project.setLinkProjectName(projectObj.getString("linkProjectName"));
		Project.setLinkProjectStage(projectObj.getString("linkProjectStage"));
		Project.setAddr(projectObj.getString("addr"));
		if(projectObj.getDate("firstStartDate") != null){
			  Project.setFirstStartDate(LocalDateTime.ofInstant(projectObj.getDate("firstStartDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("firstFinishDate") != null){
			  Project.setFirstFinishDate(LocalDateTime.ofInstant(projectObj.getDate("firstFinishDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("firstDeliveryDate") != null){
			  Project.setFirstDeliveryDate(LocalDateTime.ofInstant(projectObj.getDate("firstDeliveryDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("firstOpenDate") != null){
			  Project.setFirstOpenDate(LocalDateTime.ofInstant(projectObj.getDate("firstOpenDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("cashBackDate") != null){
			  Project.setCashBackDate(LocalDateTime.ofInstant(projectObj.getDate("cashBackDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("lastDeliveryDate") != null){
			  Project.setLastDeliveryDate(LocalDateTime.ofInstant(projectObj.getDate("lastDeliveryDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("allFinishDate") != null){
			  Project.setAllFinishDate(LocalDateTime.ofInstant(projectObj.getDate("allFinishDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("firstFinishBackDate") != null){
			  Project.setFirstFinishBackDate(LocalDateTime.ofInstant(projectObj.getDate("firstFinishBackDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("preSaleLicenceDate") != null){
			  Project.setPreSalelicenceDate(LocalDateTime.ofInstant(projectObj.getDate("preSaleLicenceDate").toInstant(), ZoneId.systemDefault()));
		}
		if(projectObj.getDate("firstEndDate") != null){
			  Project.setFirstEndDate(LocalDateTime.ofInstant(projectObj.getDate("firstEndDate").toInstant(), ZoneId.systemDefault()));
		}
		Project.setTradeObjName(projectObj.getString("tradeObjName"));
		Project.setIsInnerSystem(projectObj.getString("isInnerSystem"));
	}
    
	@Override
    public String projectStages(String apiVersion, String projectStagesInfo) {
		log.info("######ESB主数据项目分期 start##################"+ LocalDateTime.now());
		List<String> stageIds = new ArrayList<>();
		JSONObject object = (JSONObject) JSONObject.parse(projectStagesInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
    	String returnStatus = "S";
        String returnMsg = "调用成功";
        String ex ="成功";
        String isSuccess = IsSuccessEnum.SUCCESS.getKey();
    	String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		try {
			JSONObject projectStagesInfoObj =  JSON.parseObject(projectStagesInfo);
			JSONArray projectStages = projectStagesInfoObj.getJSONObject("requestInfo").getJSONObject("projectStages").getJSONArray("projectStagesInfoLine");
			if(projectStages != null && !projectStages.isEmpty()) {
				for(int i =0; i < projectStages.size(); i ++ ) {
					JSONObject  projectStageObj = projectStages.getJSONObject(i);
					String projectFid = projectStageObj.getString("projectFID");
					MdmStage Stage = stageService.selectById(projectFid);
					stageIds.add(projectFid);
					if(Stage == null) {
						Stage = new MdmStage();
						Stage.setProjectFid(projectStageObj.getString("projectFID"));
						Stage.setCreatedTime(LocalDateTime.now());
						if(StringUtils.isNotEmpty(projectStageObj.getString("isDelete"))){
							Stage.setIsDelete(projectStageObj.getString("isDelete"));
						}else{
							Stage.setIsDelete(IsDeleteEnum.NO.getKey()+"");
						}
						setStageValue(projectStageObj, Stage);
						stageService.save(Stage);
					}else {
						Stage.setUpdatedTime(LocalDateTime.now());
						setStageValue(projectStageObj, Stage);
						stageService.updateByProjectFid(Stage);
					}
					//变更分期名称
					ProjectByStages projectByStages = projectByStagesMapper.selectByPrimaryKey(projectFid);
					if (projectByStages != null){
						projectByStages.setOrgname(projectStageObj.getString("stageName"));
						projectByStagesMapper.updateByPrimaryKey(projectByStages);
					}

				}
			}
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "N";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		
		//初始化取数系统
		Thread  syncFetchNumber = new SyncFetchNumber(stageIds);
		syncFetchNumber.start();
		
		//记录日志
		Thread  saveLog = new SaveLog("项目分期数据","接收参数："+projectStagesInfo+";处理结果："+ex,isSuccess);
		saveLog.start();
		
		String returnCode = "SMS-007";
		log.info("######ESB主数据项目分期 end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime, returnCode);
    }

	private void setStageValue(JSONObject projectStageObj, MdmStage stage) {
		stage.setStageCode(projectStageObj.getString("stageCode"));
		stage.setStageName(projectStageObj.getString("stageName"));
		stage.setStatus(projectStageObj.getString("status"));
		stage.setProjectId(projectStageObj.getString("projectID"));
		stage.setProjectFid(projectStageObj.getString("projectFID"));
		stage.setKingdeeProjectId(projectStageObj.getString("kingdeeProjectID"));
		stage.setKingdeeProjectfId(projectStageObj.getString("kingdeeProjectFID"));
		stage.setTaxType(projectStageObj.getString("taxType"));
		stage.setRemark(projectStageObj.getString("remark"));
		stage.setStageOldName(projectStageObj.getString("stageOldName"));
		stage.setStagesFlag(projectStageObj.getString("stagesFlag"));
		stage.setIsDelete(projectStageObj.getString("isDelete"));
		if(projectStageObj.getDate("createdTime") != null){
			stage.setCreatedTime(LocalDateTime.ofInstant(projectStageObj.getDate("createdTime").toInstant(), ZoneId.systemDefault()));
		}
		if(projectStageObj.getDate("updatedTime") != null){
			stage.setUpdatedTime(LocalDateTime.ofInstant(projectStageObj.getDate("updatedTime").toInstant(), ZoneId.systemDefault()));
		}
		stage.setCreatedBy(projectStageObj.getString("createdBy"));
		stage.setUpdatedBy(projectStageObj.getString("updatedBy"));
		stage.setIsAuthenticRight(projectStageObj.getString("isAuthenticRight"));
			  
	}

    @Override
    public String group(String apiVersion, String groupInfo) {
    	log.info("######ESB主数据组团楼栋 start##################"+ LocalDateTime.now());
		JSONObject object = (JSONObject) JSONObject.parse(groupInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")); 
		String returnStatus = "S";
        String returnMsg = "调用成功";
        String ex ="成功";
        String isSuccess = IsSuccessEnum.SUCCESS.getKey();
        LocalDateTime now = LocalDateTime.now();
        List<MdmGroupBld> groupList = new ArrayList<>();
        try {
	        JSONObject groupItem = JSON.parseObject(groupInfo).getJSONObject("requestInfo").getJSONObject("group");
	        JSONArray groupInfoLine = groupItem.getJSONArray("groupInfoLine");
	        if(CollectionUtils.isNotEmpty(groupInfoLine)){
	            for (int i = 0;i < groupInfoLine.size(); i++){
	                MdmGroupBld groupBld = new MdmGroupBld();
	                JSONObject groupObj = groupInfoLine.getJSONObject(i);
	                groupBld.setProjectId(groupObj.getString("projectID"));
	                groupBld.setKingdeeProjectId(groupObj.getString("kingdeeProjectID"));
	                groupBld.setProjectCode(groupObj.getString("projectCode"));
	                groupBld.setProjectName(groupObj.getString("projectName"));
	                groupBld.setProjectfId(groupObj.getString("projectFID"));
	                //groupBld.setKingdeeProjectfId(groupObj.getString("kingdeeProjectfId"));
	                groupBld.setStageCode(groupObj.getString("stageCode"));
	                groupBld.setStageName(groupObj.getString("stageName"));
	                groupBld.setGroupId(groupObj.getString("groupID"));
	                groupBld.setGroupCode(groupObj.getString("groupCode"));
	                groupBld.setGroupName(groupObj.getString("groupName"));
	                groupBld.setProductCode(groupObj.getString("productCode"));
	                groupBld.setProductName(groupObj.getString("productName"));
	                groupBld.setDesignBuildId(groupObj.getString("designBuildID"));
	                groupBld.setBldPrdId(groupObj.getString("bldPrdID"));
	                groupBld.setFormatBuildingCode(groupObj.getString("formatBuildingCode"));
	                groupBld.setFormatBuildingName(groupObj.getString("formatBuildingName"));
	                groupBld.setBuildingId(groupObj.getString("buildingID"));
	                groupBld.setBuildingCode(groupObj.getString("buildingCode"));
	                groupBld.setBuildingName(groupObj.getString("buildingName"));
	                
	                String carryDateStr = groupObj.getString("planCarryDate");
	                Date planCarryDate = new Date();;
	                if(null!=carryDateStr) {
	                	planCarryDate = new Date(Long.parseLong(groupObj.getString("planCarryDate")));
	                	groupBld.setPlanCarryDate(LocalDateTime.ofInstant(planCarryDate.toInstant(), ZoneId.systemDefault()));
	                }
	                groupBld.setIsParkingGroup(groupObj.getString("isParkingGroup"));
	                groupBld.setTotalBuildArea(groupObj.getBigDecimal("totalBuildArea"));
	                groupBld.setTotalLandArea(groupObj.getBigDecimal("totalLandArea"));
	                groupBld.setVersionCode(groupObj.getString("versionCode"));
	                groupBld.setProType(groupObj.getString("proTypeCode"));
	                groupBld.setProTypeName(groupObj.getString("productType"));
	                groupBld.setBusinessType(groupObj.getString("businessTypeCode"));
	                groupBld.setBusinessTypeName(groupObj.getString("businessType"));
	                groupBld.setFreeType(groupObj.getString("freeTypeCode"));
	                groupBld.setFreeTypeName(groupObj.getString("freeType"));
	                groupBld.setVersionStage(groupObj.getString("versionStage"));
	                groupBld.setTotalSaleArea(groupObj.getBigDecimal("totalSaleArea"));
	                groupBld.setBaseBuildArea(groupObj.getBigDecimal("baseBuildArea"));
	                groupBld.setUpBuildArea(groupObj.getBigDecimal("upBuildArea"));
	                groupBld.setUnderBuildArea(groupObj.getBigDecimal("underBuildArea"));
	                groupBld.setUpSaleArea(groupObj.getBigDecimal("upSaleArea"));
	                groupBld.setUnderSaleArea(groupObj.getBigDecimal("underSaleArea"));
	                groupBld.setUpGiftArea(groupObj.getBigDecimal("upGiftArea"));
	                groupBld.setUnderGiftArea(groupObj.getBigDecimal("underGiftArea"));
	                groupBld.setFloors(groupObj.getInteger("floors"));
	                groupBld.setUnitNum(groupObj.getInteger("unitNum"));
	                groupBld.setRoomHigh(groupObj.getBigDecimal("roomHigh"));
	                groupBld.setFloorHigh(groupObj.getBigDecimal("floorHigh"));
	                groupBld.setLiftNum(groupObj.getInteger("liftNum"));
	                groupBld.setRoomNum(groupObj.getInteger("roomNum"));
	                groupBld.setStatus(groupObj.getString("status"));
	                Date approvalTime = groupObj.getDate("approvalTime");
	                if(approvalTime != null){
	                    groupBld.setApprovalTime(LocalDateTime.ofInstant(approvalTime.toInstant(), ZoneId.systemDefault()));
	                }
	                groupBld.setCreateTime(now);
	                groupList.add(groupBld);
	            }
	        }
	        groupBldService.saveBatch(groupList);
        } catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "N";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
        //记录日志 
		Thread  saveLog = new SaveLog("组团楼栋关系数据","接收参数："+groupInfo+";处理结果："+ex,isSuccess);
		saveLog.start();
        
        String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
        log.info("######ESB主数据组团楼栋 end##################"+ LocalDateTime.now());
        return createEsbReturnJson(instId,returnStatus,returnMsg, requestTime, responseTime, "SMS-008");
    }

	@Override
	public String partner(String apiVersion, String partnerInfo) {
		log.info("######ESB主数据项目合作方 start##################"+ LocalDateTime.now());
		String returnStatus = "S";
 		String returnMsg = "调用成功";
 		String ex ="成功";
 		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		JSONObject object = (JSONObject) JSONObject.parse(partnerInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		try {
			JSONObject partnerInfoObj =  JSON.parseObject(partnerInfo);
			JSONArray projectPartners = partnerInfoObj.getJSONArray("requestInfo");
			if(projectPartners != null && !projectPartners.isEmpty()) {
				for(int i =0; i < projectPartners.size(); i ++ ) {
					JSONObject  partnerObj = projectPartners.getJSONObject(i);
					String projectId = partnerObj.getString("projectID");
					String partnerNo = partnerObj.getString("partnerNo");
					MdmProjectPatner projectPatner = projectPatnerService.selectByProjectIdAndPartnerNo(projectId,partnerNo);
					if(projectPatner == null) {
						projectPatner = new MdmProjectPatner();
						setProjectPatnerValue(partnerObj, projectPatner);
						projectPatner.setCreatedTime(LocalDateTime.now());
						projectPatnerService.save(projectPatner);
					}else {
						setProjectPatnerValue(partnerObj, projectPatner);
						projectPatner.setUpdatedTime(LocalDateTime.now());
						projectPatnerService.updateByProjectIdAndPartnerNo(projectPatner);
					}
				}
			}
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "N";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志
		Thread  saveLog = new SaveLog("项目合作方数据","接收参数："+partnerInfo+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB主数据项目合作方 end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-013");
	}
	
	private void setProjectPatnerValue(JSONObject partnerObj, MdmProjectPatner projectPatner) {
		projectPatner.setProjectId(partnerObj.getString("projectID"));
		projectPatner.setPartnerNo(partnerObj.getString("partnerNo"));
		projectPatner.setKingdeeProjectId(partnerObj.getString("kingdeeProjectID"));
		projectPatner.setPartner(partnerObj.getString("partner"));
		projectPatner.setIsProjectManager(partnerObj.getString("isProjectManager"));
		projectPatner.setIsAndTable(partnerObj.getString("isAndTable"));
		projectPatner.setEquityRatio(StrUtils.stringToBigDecimal(partnerObj.getString("equityRatio")));
		projectPatner.setIsOpProcurement(partnerObj.getString("isOPProcurement"));
		projectPatner.setIsOpFinance(partnerObj.getString("isOPFinance"));
		projectPatner.setIsOpCost(partnerObj.getString("isOPCost"));
		projectPatner.setIsOpLegal(partnerObj.getString("isOPLegal"));
		projectPatner.setIsOpProject(partnerObj.getString("isOPProject"));
		projectPatner.setIsOpOffice(partnerObj.getString("isOPOffice"));
		projectPatner.setIsOpService(partnerObj.getString("isOPService"));
		projectPatner.setIsOpMating(partnerObj.getString("isOPMating"));
		projectPatner.setIsOpDesign(partnerObj.getString("isOPDesign"));
		projectPatner.setIsHoldManagement(partnerObj.getString("isHoldManagement"));
		projectPatner.setIsOpMarketing(partnerObj.getString("isOPMarketing"));
		projectPatner.setIsOpOperation(partnerObj.getString("isOPOperation"));
		Date createdTime = partnerObj.getDate("createdTime");
		if(createdTime != null){
			projectPatner.setCreatedTime(LocalDateTime.ofInstant(partnerObj.getDate("createdTime").toInstant(), ZoneId.systemDefault()));
		}
		projectPatner.setCreatedBy(partnerObj.getString("updatedBy"));
		if(createdTime != null){
			projectPatner.setUpdatedTime(LocalDateTime.ofInstant(partnerObj.getDate("updatedBy").toInstant(), ZoneId.systemDefault()));
		}
		projectPatner.setUpdatedBy(partnerObj.getString("updatedBy"));
		if(StringUtils.isNotEmpty(partnerObj.getString("isDelete"))){
			projectPatner.setIsDelete(partnerObj.getString("isDelete"));
		}else{
			projectPatner.setIsDelete(IsDeleteEnum.NO.getKey()+"");
		}
	}

	@Override
	public String formatArea(String apiVersion, String formatAreaInfo) {
		JSONObject object = (JSONObject) JSONObject.parse(formatAreaInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		return createEsbReturnJson(instId, "S", "调用成功", requestTime, requestTime,"SMS-010");
	}

	/**
	 * 楼栋业态面积版本变更接收(主数据)
	 */
	@Override
	public String buildFormatArea(String apiVersion, String buildFormatAreaInfo) {
		log.info("######主数据楼栋业态面积 start##################"+ LocalDateTime.now());
		JSONObject object = (JSONObject) JSONObject.parse(buildFormatAreaInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		LocalDateTime now = LocalDateTime.now();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		Map<String, String> stageMapIds = new HashMap<String, String>();
		try {
			stageMapIds = buildAreaService.saveArea(buildFormatAreaInfo, stageMapIds, now);
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "N";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}

		//刷新货值信息
        Thread buildFormatAreaTodo = new BuildFormatAreaTodo(instId,stageMapIds);
        buildFormatAreaTodo.start();

		//记录日志
		Thread  saveLog = new SaveLog("楼栋业态面积数据","接收参数："+buildFormatAreaInfo+";处理结果："+ex,isSuccess);
		saveLog.start();
		
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######主数据楼栋业态面积 end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-011");
		
	}

	 /**
	 * 楼栋计划变更
	 */
	public String buildingPlan(String apiVersion, String buildingPlanInfo) {
		log.info("######主数据楼栋计划start##################"+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		String versionType = "";
		String stageId = ""; 
		JSONObject object = (JSONObject) JSONObject.parse(buildingPlanInfo);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		try {
			requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
			JSONObject buildingPlanObj = JSON.parseObject(buildingPlanInfo).getJSONObject("requestInfo")
					.getJSONObject("buildingPlan").getJSONObject("buildingPlanInfoLine");
			Map<String, Object> map = panoplanBuildPlanService.syncPanoplanBuildPlan(buildingPlanObj);
			Set<Map.Entry<String, Object>> entries = map.entrySet();
			for (Map.Entry<String, Object> entry : entries) {
				if (entry.getKey().equals("versionType")) {
					versionType = String.valueOf(entry.getValue());
				}  else if (entry.getKey().equals("projectfID")) {
					stageId = String.valueOf(entry.getValue());
				} 
			}
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}

		//刷新楼栋计划信息
		Thread refreshPriceVersionByPano = new RefreshPriceVersionByPano(versionType, stageId, instId);
		refreshPriceVersionByPano.start();

		//记录日志 
		Thread  saveLog = new SaveLog("楼栋计划数据","接收参数："+buildingPlanInfo+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######主数据楼栋计划end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-001");
		
	}

	/**
	 *  1.定价：供销存初次获取的房源，为定价。
		2.调价：本次订阅涉及价格字段发生变更，为调价。
		3.签约：本次订阅的变更房源状态为【签约】，且房源上一条历史记录状态不是【签约】，为签约。
		4.退房：本次订阅的变更房源状态为【待售】，且房源上一条历史记录状态是【签约】，为退房。
		5.面积变更：本次订阅涉及面积字段发生变更，为面积变更（可区分预测、实测）
	 */
	@Override
	public String rooms(String apiVersion, String rooms) {
		log.info("######明源房间变更start##################"+ LocalDateTime.now());
		LocalDateTime now = LocalDateTime.now();
		JSONObject object = (JSONObject) JSONObject.parse(rooms);
		String instId = String.valueOf(object.getJSONObject("esbInfo").get("instId"));
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		try {
			 mymRoomInfoService.updateRooms(rooms, now, instId);
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess= IsSuccessEnum.FAIL.getKey();
		}
		//记录日志 
		Thread  saveLog = new SaveLog("明源房间变更","接收参数："+rooms+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######明源房间变更end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-012");
	}

	@Override
	public String contracts(String apiVersion, String contracts) {
		log.info("######明源签约数据变更start##################"+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		JSONObject signDataObject = JSON.parseObject(contracts);
		JSONObject esbInfo = signDataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		try{
			JSONArray array = signDataObject.getJSONArray("requestInfo");
			if(array != null && !array.isEmpty()) {
				List<DmOdsMyVsMarsSContract> contractList = Collections.synchronizedList(new ArrayList<>());
				for(int i =0; i < array.size(); i ++ ) {
					JSONObject  object = array.getJSONObject(i);
					DmOdsMyVsMarsSContract contract = new DmOdsMyVsMarsSContract();
					contract.setXmprojguid(object.getString("xmprojguid"));
					contract.setXmprojname(object.getString("xmprojname"));
					contract.setXIsyxcp(object.getString("x_IsYxCp"));
					contract.setKingdeexmprojguid(object.getString("kingdeexmprojguid"));
					contract.setPProjectid(object.getString("p_projectId"));
					contract.setProjName(object.getString("ProjName"));
					contract.setKingdeeprojguid(object.getString("kingdeeprojguid"));
					contract.setProductTypeGUID(object.getString("ProductTypeGUID"));
					contract.setProductName(object.getString("ProductName"));
					contract.setBldguid(object.getString("BldGUID"));
					contract.setBldPrdID(object.getString("bldPrdID"));
					contract.setBldname(object.getString("BldName"));
					contract.setRoomGUID(object.getString("RoomGUID"));
					contract.setRoomInfo(object.getString("RoomInfo"));
					contract.setStatus(object.getString("Status"));
					contract.setBldArea(object.getString("BldArea"));
					contract.setCjRmbTotal(object.getString("CjRmbTotal"));

					LocalDateTime ywgsDate = LocalDateTimeUtils.strToDate(object.getString("YwgsDate"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					ywgsDate = ywgsDate != null ? ywgsDate : LocalDateTimeUtils.strToDate(object.getString("YwgsDate"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setYwgsDate(ywgsDate);
					LocalDateTime closeDate = LocalDateTimeUtils.strToDate(object.getString("CloseDate"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					closeDate = closeDate != null ? closeDate : LocalDateTimeUtils.strToDate(object.getString("CloseDate"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setCloseDate(closeDate);
					contract.setCloseReason(object.getString("CloseReason"));
					contract.setBcTotal(object.getString("BcTotal"));
					contract.setBcArea(object.getString("BcArea"));

					LocalDateTime auditDate = LocalDateTimeUtils.strToDate(object.getString("AuditDate"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					auditDate = auditDate != null ? auditDate : LocalDateTimeUtils.strToDate(object.getString("AuditDate"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setAuditDate(auditDate);
					LocalDateTime createdTime = LocalDateTimeUtils.strToDate(object.getString("CreatedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					createdTime = createdTime != null ? createdTime : LocalDateTimeUtils.strToDate(object.getString("CreatedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setCreatedTime(createdTime);
					LocalDateTime modifiedTime = LocalDateTimeUtils.strToDate(object.getString("ModifiedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					modifiedTime = modifiedTime != null ? modifiedTime : LocalDateTimeUtils.strToDate(object.getString("ModifiedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setModifiedTime(modifiedTime);
					LocalDateTime bCCreatedTime = LocalDateTimeUtils.strToDate(object.getString("BCCreatedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					bCCreatedTime = bCCreatedTime != null ? bCCreatedTime : LocalDateTimeUtils.strToDate(object.getString("BCCreatedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setBCCreatedTime(bCCreatedTime);
					LocalDateTime bCModifiedTime = LocalDateTimeUtils.strToDate(object.getString("BCModifiedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_ONE));
					bCModifiedTime = bCModifiedTime != null ? bCModifiedTime : LocalDateTimeUtils.strToDate(object.getString("BCModifiedTime"), DateTimeFormatter.ofPattern(DateUtils.DATE_KEY_FULL_STR_TWO));
					contract.setBCModifiedTime(bCModifiedTime);

					contract.setTradeGUID(object.getString("TradeGUID"));
					contract.setX_kingdeesignguid(object.getString("x_kingdeesignguid"));
					contract.setContractGUID(object.getString("ContractGUID"));
					contractList.add(contract);
				}
//				//TODO 明源签约数据改成ESB下发，上线需修改
//				dmOdsMyVsMarsSContractService.syncByEsbData(contractList);
			}
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}

		//记录日志
		Thread  saveLog = new SaveLog("明源签约数据变更","接收参数："+contracts+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######明源签约数据变更end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"");
	}

	/**
	 * 当月签约计划
	 * @return
	 */
	@Override
	public String monthTradePlan(String apiVersion, String signData) {
		log.info("######签约计划start##################"+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		JSONObject signDataObject = JSON.parseObject(signData);
		JSONObject esbInfo = signDataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		try{
			JSONArray requestInfo = signDataObject.getJSONArray("requestInfo");
			//获取分期列表
			Set<String> set = monthTradePlanService.insertMonthTradePlanData(requestInfo);
			//异步处理,对签约计划做倒挤
			Runnable runnable = new Runnable() {
				@Override
				public void run() {
					for (String stageId : set) {
						signPlanVersionService.insertDynamicSignPlanVersion(stageId);
					}
				}
			};
			runnable.run();
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志
		Thread  saveLog = new SaveLog("签约计划订阅","接收参数："+signData+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######签约计划end##################"+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-014");
	}
	
	/**
	 * 分期合作方同步Rest接口
	 */
	@Override
	public String syncStagePartners(String apiVersion, String data) {
		log.info("######ESB分期合作方同步 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		JSONObject signDataObject = JSON.parseObject(data);
		JSONObject esbInfo = signDataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		try{
			JSONObject requestInfo = signDataObject.getJSONObject("requestInfo");
			//获取分期列表
			stagePartNersService.syncStagePartners(requestInfo);
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.SUCCESS.getKey();
		}
		//记录日志
		Thread  saveLog = new SaveLog("分期合作方","接收参数："+data+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB分期合作方同步 end##################："+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-015");
	}
	
	/**
	 * 全景计划-拿地时间(全景计划接口订阅)
	 */
	@Override
	public String panoramaPlan(String apiVersion, String signData) {
		log.info("######ESB全景计划同步 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		JSONObject signDataObject = JSON.parseObject(signData);
		JSONObject esbInfo = signDataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		try{
			JSONObject requestInfo = signDataObject.getJSONObject("requestInfo");
			//全景计划-拿地时间(全景计划接口订阅)
			panoramaService.panoramaPlan(requestInfo);
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志 
		Thread  saveLog = new SaveLog("全景计划接口订阅","接收参数："+signData+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB全景计划同步 end##################："+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-015");
	}

	/**
	 * 校验是否允许明源做定调价
	 * @param apiVersion
	 * @param msg
	 * @return
	 */
	@Override
	public String isAllowModify(String apiVersion, String msg) {
		log.info("######ESB校验是否允许明源做定调价 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		String responseTime = null;
		JSONObject requestData = JSON.parseObject(msg);
		JSONObject requestEsbInfo = requestData.getJSONObject("esbInfo");
		String instId = requestEsbInfo.getString("instId");
		Map<String,Object> responseDate = new HashMap<>();
		Map<String,Object> data = new HashMap<>();
		try{
			List<Map<String,Object>> stageItems = new ArrayList<>();
			//项目是否锁定标记
			boolean isLock = false;
			//战规后版本类型列表
			List<String> versionTypes = Arrays.asList(VersionTypeEunm.WARPLAN.getKey(),VersionTypeEunm.GETPRICE.getKey(),VersionTypeEunm.DYNAMIC.getKey());
			//货值版本类型列表
			List<String> existVersionTypes = Arrays.asList(VersionTypeEunm.INVESTMENT.getKey(),VersionTypeEunm.WARPLAN.getKey(),VersionTypeEunm.GETPRICE.getKey(),VersionTypeEunm.DYNAMIC.getKey());
			//在途版本状态列表
			List<String> existVersionStates =  Arrays.asList(VersionStatusEnum.NOTPREPARED.getKey(), VersionStatusEnum.ORGANIZATION.getKey(), VersionStatusEnum.EXAMINEDAPPROVED.getKey(), VersionStatusEnum.APPROVED.getKey(),VersionStatusEnum.FAILUREAPPROVED.getKey() );
			List<String> stageIdList = new ArrayList<>();
			JSONObject requestInfo = JSONObject.parseObject(requestData.getString("requestInfo"));

			String projectId = requestInfo.getString("projectId");
			String schemeId = requestInfo.getString("schemeId");
			JSONArray requestStageDataArr = requestInfo.getJSONArray("stageItems");
			for(Object requestStageData : requestStageDataArr){
				Map<String,Object> responseStageMap = new HashMap<>();
				//分期是否允许定调价标记（true-允许；false-不允许）
				boolean isAllow = true;
				//分期数据
				JSONObject requestStage = JSONObject.parseObject(requestStageData.toString());
				//分期ID
				String stageId = requestStage.getString("id");
				stageIdList.add(stageId);
				//在全盘最新的规则下,获取分期下最新的货值版本
				PriceVersion priceVersion = priceVersionService.getNewestPriceVersion(stageId);
				if(null == priceVersion){
					responseStageMap.put("remark","供销存系统分期下不存在审批通过的货值版本");
					isAllow = false;
				}else {
					if(!versionTypes.contains(priceVersion.getVersionType())){
						responseStageMap.put("remark","供销存系统不存在战规后的货值版本");
						isAllow = false;
					}else {
						//版本阶段
						String versionStage = requestStage.getString("versionStage");
						//版本号
						String versionNum = requestStage.getString("versionNum");
						if(!priceVersion.getSourceAreaVersionStage().equals(versionStage) || !priceVersion.getSourceAreaVersionNum().equals(versionNum)) {
							responseStageMap.put("remark", "当前明源系统面积版本与供销存全盘最新的货值版本基于的主数据面积版本不一致，请保证两系统一致再进行定调价！");
							isAllow = false;
						}
					}
                    if(MarketingEunm.IS_NOT_MARKET.getKey().equals(priceVersion.getIsMarket())){
                        responseStageMap.put("remark", "分期为非营销操盘");
                        isAllow = false;
                    }
					responseStageMap.put("tradeMode",priceVersion.getIsMarket());
				}
				responseStageMap.put("id",stageId);
				responseStageMap.put("isAllow",isAllow);
				stageItems.add(responseStageMap);
				if(isAllow){
					isLock = true;
				}
			}

			for (String stageId: stageIdList){
				//项目分期下是否存在在途的货值版本
                List<PriceVersion> priceVersions = priceVersionMapper.selectApprovalVersionByFidAndTypesAndStates(stageId, existVersionTypes, existVersionStates, IsDeleteEnum.NO.getKey());
                if(CollectionUtils.isNotEmpty(priceVersions)){
                    stageItems.forEach(s->{
                    	if(s.get("id").equals(stageId)) {
                    		 s.put("isAllow",false);
                             s.put("remark","当前供销存系统存在在途（草稿，审批中，被驳回）的货值版本，请处理掉在途货值版本再进行定调价！");
                    	}
                    });
                    isLock = false;
                    break;
                }
            }

            //查询项目是否锁定
            boolean projectIsLock = projectLockRecordService.isLockByProjectId(projectId);
			if(projectIsLock){
                //根据项目id、方案id查询未解锁记录
                List<ProjectLockRecord> projectLockRecordList  = projectLockRecordMapper.selectByProjectIdAndSchemeId(projectId,schemeId);
                if(CollectionUtils.isNotEmpty(projectLockRecordList)){
                    stageItems.forEach(s->{
                        s.put("remark","当前项目明源系统存在在途的方案");
                    });
                }else {
                    stageItems.forEach(s->{
                        s.put("isAllow",false);
                        s.put("remark","当前项目明源系统存在在途的方案");
                    });
                }
                //已锁定项目不必要重复锁定
                isLock = false;
            }
			if(isLock){
				//添加项目锁定记录
				projectLockRecordService.add(requestInfo.getString("projectId"),requestInfo.getString("schemeId"),stageItems.toString());
			}
            data.put("stageItems",stageItems);
            responseDate.put("resultInfo",data);
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		
		EsbInfo responseEsbInfo = toEsbInfo(instId, returnStatus, returnMsg, requestTime, responseTime, "A0001-SMS");
		responseDate.put("esbInfo",responseEsbInfo);
		
		//记录日志 
		Thread  saveLog = new SaveLog("校验是否允许明源定调价", "接收参数："+msg+";处理结果："+ex +";"+"响应结果："+JSON.toJSONString(responseDate),isSuccess);
		saveLog.start();
		log.info("######ESB校验是否允许明源做定调价 end##################："+ LocalDateTime.now());
		return JSON.toJSONString(responseDate);
	}

	/**
	 * 供销存-明源定调价通知
	 * @param apiVersion
	 * @param msg
	 * @return
	 */
	@Override
	public String modifyNotice(String apiVersion, String msg) {
		log.info("######ESB明源定调价通知 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		JSONObject requestData = JSON.parseObject(msg);
		JSONObject requestEsbInfo = requestData.getJSONObject("esbInfo");
		String instId = requestEsbInfo.getString("instId");
		try {
			JSONObject requestInfo = JSONObject.parseObject(requestData.getString("requestInfo"));
			String projectId = requestInfo.getString("projectId");
			String projectCode = requestInfo.getString("projectCode");
			String status = requestInfo.getString("status");
			String schemeId = requestInfo.getString("schemeId");
			JSONArray areaItems = requestInfo.getJSONArray("areaItems");
			//如果项目已解锁，则不能刷新
			boolean lockBySchemeId = projectLockRecordService.isLockBySchemeId(schemeId);
			if (!lockBySchemeId){
				String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
				return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-016");
			}
			
			//discard- 废弃、execute- 执行
			if(status.equals("discard")){
				String lockRecordId = projectLockRecordService.update(projectId, projectCode, schemeId, areaItems.toString());
				//刷新待办信息
				Thread noticeRefreshByDiscard = new NoticeRefreshByDiscard(projectId);
				noticeRefreshByDiscard.start();
			}else if(status.equals("execute")){
				//刷新明源规划信息
				Thread refreshPriceVersionByPlanRecord = new RefreshPriceVersionByPlanRecord(projectId, projectCode, schemeId, instId, areaItems);
				refreshPriceVersionByPlanRecord.start();
				
				String result = queryXGPriceValue(VersionConstant.V1,schemeId);
				JSONObject resData = JSON.parseObject(result);
				JSONObject resDataInfo = JSONObject.parseObject(resData.getString("resultInfo"));
				if(resDataInfo != null) {
					JSONObject data = JSONObject.parseObject(resDataInfo.getString("data"));
					if(data != null) {
						String flow_status = data.getString("flow_status");
						if(StrUtils.isNotEmpty(flow_status) && flow_status.equals("4")) {
							priceVersionGroupService.saveGroupRefreshRecord(projectId,schemeId);
						}
					}
				}
				
			}
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志 
		Thread  saveLog = new SaveLog("明源定调价通知","接收参数："+msg+";处理结果："+ex,isSuccess);
		saveLog.start();
		String responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB明源定调价通知 end##################："+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-016");
	}

	private EsbInfo toEsbInfo(String instId, String returnStatus, String returnMsg, String requestTime, String responseTime, String returnCode) {
		EsbInfo esbInfo = new EsbInfo();
		esbInfo.setAttr1("null");
		esbInfo.setAttr2("null");
		esbInfo.setAttr3("null");
		esbInfo.setInstId(instId);
		esbInfo.setRequestTime(requestTime);
		esbInfo.setResponseTime(responseTime);
		esbInfo.setReturnCode(returnCode);
		esbInfo.setReturnMsg(returnMsg);
		esbInfo.setReturnStatus(returnStatus);
		return esbInfo;
	}

	class NoticeRefreshByDiscard extends Thread{
		private String projectId;

		public NoticeRefreshByDiscard(String projectId){
			this.projectId=projectId;
		}
		public void run() {
			boolean isLocked = synchrolockUtil.islocked(Constants.RedisSyncKey);
			try {
				projectLockRecordDetailService.recordNoticeRefreshToUnlock(projectId, LocalDateTime.now());
			} catch (MsgException e) {
				logger.error("####################  明源规划信息业务错误信息:" + e.getMsg(), e);
			} catch (Exception e) {
				logger.error("####################  明源规划信息错误:" + e.getMessage(), e);
			}finally {
				synchrolockUtil.unlock(Constants.RedisSyncKey);
				logger.info("====同步锁解锁成功====");
			}
		}
	}

	class RefreshPriceVersionByPlanRecord extends Thread{
		private String projectId;
		private String projectCode;
		private String schemeId;
		private String instId;
		private JSONArray areaItems;

		public RefreshPriceVersionByPlanRecord(String projectId,String projectCode,String schemeId, String instId,JSONArray areaItems) {
			this.projectId=projectId;
			this.projectCode=projectCode;
			this.schemeId=schemeId;
			this.instId=instId;
			this.areaItems=areaItems;
		}

		public void run() {
			boolean isLocked = synchrolockUtil.islocked(Constants.RedisSyncKey);
			logger.info("====同步锁加锁状态："+isLocked);
			try {
				projectLockRecordDetailService.refreshPriceVersion(projectId, projectCode, schemeId, instId, areaItems);
				
			} catch (MsgException e) {
				logger.error("####################  明源规划信息业务错误信息" + e.getMsg(), e);
			} catch (Exception e) {
				logger.error("####################  明源规划信息错误" + e.getMessage(), e);
			}finally {
				synchrolockUtil.unlock(Constants.RedisSyncKey);
				logger.info("====同步锁解锁成功====");
			}
		}
	}
	
	/**
	 * 预算季预算版本标识接口
	 */
	@Override
	public String projectVersion(String apiVersion, String msg) {
		log.info("######ESB预算季预算版本标识接口 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		String responseTime = null;
		JSONObject dataObject = JSON.parseObject(msg);
		JSONObject esbInfo = dataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		try{
			JSONObject requestInfo = dataObject.getJSONObject("requestInfo");
			if(requestInfo != null) {
				String isBudget = requestInfo.getString("isBugdet");
				String version = requestInfo.getString("version");
				String versionCode = requestInfo.getString("versionCode");
				//更新保存预算季预算版本标识
				budgetVersionIdentifyService.updateVersionIdentify(isBudget,versionCode,version);
			}
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志
		Thread  saveLog = new SaveLog("预算版本标识接口","接收参数："+msg+";处理结果："+ex,isSuccess);
		saveLog.start();
		responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB预算季预算版本标识接口 end##################："+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-019");
	}

	/**
	 * 预算季是否允许编制版本接口
	 */
	@Override
	public String projectStatus(String apiVersion, String msg) {
		log.info("######ESB预算季是否允许编制版本接口 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		String responseTime = null;
		JSONObject dataObject = JSON.parseObject(msg);
		JSONObject esbInfo = dataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		List<BudgetLockRecord> list = new ArrayList<>();
		try{
			JSONArray requestInfo = dataObject.getJSONArray("requestInfo");
			if(requestInfo != null && !requestInfo.isEmpty()) {
				for(int i =0; i < requestInfo.size(); i ++ ) {
					JSONObject  obj = requestInfo.getJSONObject(i);
					String projectId = obj.getString("projectId");
					String version = obj.getString("version");
					String signIsAllow = obj.getString("signIsAllow");
					String returnIsAllow = obj.getString("returnIsAllow");
					
					BudgetLockRecord record = new  BudgetLockRecord();
					record.setProjectId(projectId);
					record.setVersionIdentify(version);
					if(StrUtils.isNotEmpty(signIsAllow) && signIsAllow.equals("true")) {
						record.setSignLock(WhetherEnum.NO.getKey());
						record.setSignUnlockTime(LocalDateTime.now());
					}else {
						record.setSignLock(WhetherEnum.YES.getKey());
						record.setSignLockTime(LocalDateTime.now());
					}
					
					if(StrUtils.isNotEmpty(returnIsAllow) && returnIsAllow.equals("true")) {
						record.setReturnLock(WhetherEnum.NO.getKey());
						record.setReturnUnlockTime(LocalDateTime.now());
					}else {
						record.setReturnLock(WhetherEnum.YES.getKey());
						record.setReturnLockTime(LocalDateTime.now());
					}
					record.setCreateTime(LocalDateTime.now());
					list.add(record);
				}
				
				//更新项目预算编制锁定状态
				budgetLockRecordService.handleProjectLockStatus(list);
			}
		}catch (Exception e){
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志
		Thread  saveLog = new SaveLog("预算季是否允许编制版本接口","接收参数："+msg+";处理结果："+ex,isSuccess);
		saveLog.start();
		responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB预算季是否允许编制版本接口 end##################："+ LocalDateTime.now());
		return createEsbReturnJson(instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-018");
	}

	@Override
	public String queryPriceValue(String apiVersion, String msg) {
		log.info("######ESB查询货值核心指标接口 start##################："+ LocalDateTime.now());
		String returnStatus = "S";
		String returnMsg = "调用成功";
		String ex ="成功";
		String isSuccess = IsSuccessEnum.SUCCESS.getKey();
		String requestTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		String responseTime = null;
		JSONObject dataObject = JSON.parseObject(msg);
		JSONObject esbInfo = dataObject.getJSONObject("esbInfo");
		String instId = esbInfo.getString("instId");
		JSONObject requestInfo = dataObject.getJSONObject("requestInfo");
		PriceCoreValueBO bo = new PriceCoreValueBO();
		try {
			if(requestInfo != null) {
				String projectId =  requestInfo.getString("projectId");
				 bo = priceVersionGroupService.queryPriceValue(projectId);
			}
		} catch (Exception e) {
			log.error("###### errorMsg: ", e);
			returnStatus = "E";
			returnMsg = "调用失败";
			ex = ExceptionUtils.getExceptionAllinformation(e);
			isSuccess = IsSuccessEnum.FAIL.getKey();
		}
		//记录日志
		Thread  saveLog = new SaveLog("查询货值核心指标接口","接收参数："+msg+";处理结果："+ex,isSuccess);
		saveLog.start();
		responseTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
		log.info("######ESB查询货值核心指标接口 end##################："+ LocalDateTime.now());
		return createReturnJson(bo,instId, returnStatus, returnMsg, requestTime, responseTime,"SMS-021");
	}
	
	private String createReturnJson(PriceCoreValueBO bo,String instId, String returnStatus, String returnMsg, String requestTime,
			String responseTime, String returnCode) {
		EsbCoreValueVO vo = new EsbCoreValueVO();
		EsbInfo esbInfo = new EsbInfo();
		esbInfo.setInstId(instId);
		esbInfo.setReturnStatus(returnStatus);
		esbInfo.setReturnCode(returnCode);
		esbInfo.setReturnMsg(returnMsg);
		esbInfo.setRequestTime(requestTime);
		esbInfo.setResponseTime(responseTime);
		vo.setEsbInfo(esbInfo);
		vo.setRequestInfo(bo);
		return JsonUtils.convertObjectToJson(vo);
	}
	
	private String createEsbReturnJson(String instId, String returnStatus, String returnMsg, String requestTime,
			String responseTime, String returnCode) {
		EsbInfo esbInfo = new EsbInfo();
		esbInfo.setAttr1("null");
		esbInfo.setAttr2("null");
		esbInfo.setAttr3("null");
		esbInfo.setInstId(instId);
		esbInfo.setRequestTime(requestTime);
		esbInfo.setResponseTime(responseTime);
		esbInfo.setReturnCode(returnCode);
		esbInfo.setReturnMsg(returnMsg);
		esbInfo.setReturnStatus(returnStatus);
		EsbReturnVo returnVo = new EsbReturnVo();
		returnVo.setEsbInfo(esbInfo);
		return JsonUtils.convertObjectToJson(returnVo);
	}
	
	@Override
	public String publicSignPlan(String apiVersion,String versionId) {
		signPlanVersionDetailService.sendSignPlan(versionId,1);
		return "成功";
	}

	@Override
	public String publicSignPlanBatch(String apiVersion, String regionId, String projectId, String versionType) {
		signPlanVersionDetailService.sendSignPlanBatch(regionId,projectId,versionType);
		return "成功";
	}
	
	@Override
	public String informFetch(String apiVersion, String projectId) {
		signPlanVersionDetailService.sendInformFetch(projectId,1);
		return "成功";
	}
	
	@Override
	public String queryXGPriceValue(String apiVersion,String schemeId) {
		EsbXgReqParam param = new EsbXgReqParam();
		JSONObject data = new JSONObject();
		data.put("TjPlanGUID", schemeId);
		param.setRequestInfo(data);
		JSONObject requestInfo = new JSONObject();
		requestInfo.put("data", data);
		param.setRequestInfo(requestInfo);
		EsbInfoReq esbInfo = new EsbInfoReq();
		esbInfo.setAttr1("null");
		esbInfo.setAttr2("null");
		esbInfo.setAttr3("null");
		esbInfo.setInstId("");
		esbInfo.setRequestTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
		param.setEsbInfo(esbInfo);
		
		BasicAuthClient bac = new BasicAuthClient();
		String result =  bac.post(xgQueryUrl, JSON.toJSONString(param),apiName,apiKey);
		log.info("##### 查询销管货值审批核心指标数据接口 参数："+ JSON.toJSONString(param));
		log.info("##### 查询销管货值审批核心指标数据接口 响应数据："+ result);
		return result;
	}
	
	class BuildFormatAreaTodo extends Thread{
    	private String instId;
    	private Map<String, String> stageMapIds;
    	public BuildFormatAreaTodo(String instId,Map<String, String> stageMapIds) {
            this.instId=instId;
            this.stageMapIds=stageMapIds;            
        }
    	public void run() {
		boolean isLocked = synchrolockUtil.islocked(Constants.RedisSyncKey);
		logger.info("====同步锁加锁状态："+isLocked);
    		try {
    			///插入待办信息
    			if (CollectionUtils.isNotEmpty(stageMapIds)){
    				for (Map.Entry<String, String> stageMapId : stageMapIds.entrySet()){
    					String stageId = stageMapId.getKey();
    					String versionType = stageMapId.getValue();
    					try{
    						priceVersionValueOrgService.panoDynamicVersionChange(stageId, VersionTypeEunm.getKey(versionType), "area", instId);
						}catch (Exception e){
							logger.error("############  主数据代办信息错误  stageId:"+stageId+"   ###  e:"+e.getMessage(), e);
						}
    				}
    			}
    		}catch (Exception e){
    			logger.error("############  主数据代办信息错误 :"+ e.getMessage(), e);
    		}finally {
			synchrolockUtil.unlock(Constants.RedisSyncKey);
			logger.info("====同步锁解锁成功====");
		}
    	}
    }
	
	class RefreshPriceVersionByPano extends Thread{
		private String versionType;
		private String stageId;
		private String instId;
		public RefreshPriceVersionByPano(String versionType,String stageId,String instId) {
			this.versionType=versionType;
			this.stageId=stageId;
			this.instId=instId;
		}

		public void run() {
			boolean isLocked = synchrolockUtil.islocked(Constants.RedisSyncKey);
			logger.info("====同步锁加锁状态："+isLocked);
			try {
				if (versionType.equals(VersionTypeEunm.INVESTMENT.getValue())) {
					priceVersionValueOrgService.panoCastDecisionVersionChange(stageId, instId);
				} else {
					// 插入待办信息
					priceVersionValueOrgService.panoDynamicVersionChange(stageId, VersionTypeEunm.getKey(versionType), "pano", instId);
				}
			} catch (Exception e) {
				logger.error("####################  楼栋计划待办信息错误 #### build-plan error :" + e.getMessage(), e);
			}finally {
				synchrolockUtil.unlock(Constants.RedisSyncKey);
				logger.info("====同步锁解锁成功====");
			}
		}
	}
	
	class SyncOrgFromIdm extends Thread{
    	private List<String> projectIds;
		public SyncOrgFromIdm(List<String> projectIds) {
			super();
			this.projectIds = projectIds;
		}
		@Override
		public void run() {
			//增量组织机构同步
			String timestamp = StrUtils.getTimeStamp2(24);
	    	List<String> orgdepids = orgService.getOrgdepidList();
	    	List<String> projectList = orgService.incrementSyncIdmOrg("*",timestamp,"0",orgdepids,new ArrayList<>());
	    	//清洗项目层级
			orgService.addByStagesV2();
			//增量同步主数据到项目取数表
			if(CollectionUtils.isNotEmpty(projectIds)) {
				for(String projectId : projectIds) {
					sysProjectFetchNumberService.syncProjectFetchNumber(projectId,null);
				}
			}
		}
    }
    
    class SyncFetchNumber extends Thread{
    	private List<String> stageIds;
		public SyncFetchNumber(List<String> stageIds) {
			super();
			this.stageIds = stageIds;
		}
		@Override
		public void run() {
			//增量同步主数据到项目取数表
			if(CollectionUtils.isNotEmpty(stageIds)) {
				for(String stageId : stageIds) {
					sysProjectFetchNumberService.syncProjectFetchNumber(null,stageId);
				}
			}
		}
    }
	
	
	class SaveLog extends Thread{
    	private String title;
    	private String content;
    	private String isSuccess;
    	
		public SaveLog(String title,String content,String isSuccess) {
			super();
			this.title = title;
			this.content = content;
			this.isSuccess = isSuccess;
		}
		@Override
		public void run() {
	   		SysLogBO bo = new SysLogBO();
	   		bo.setEvent(LogEventEnum.ESB);
	       	bo.setSource(LogSrcEnum.PC);
	       	bo.setIp(WebUtils.getLocalIP());
	       	bo.setModule("ESB数据接收");
	       	bo.setTitle(title);
	       	bo.setContent(content);
	       	bo.setType(LogTypeEnum.ONE.getKey());
	       	bo.setIsSuccess(isSuccess);
	       	sysLogService.add(bo,"sys");
		}
    }

}
